<template>
  <div class="app-container">
    <div style="display:flex;align-items:center">
      <el-button type="primary" @click="handleAddRole">创建角色</el-button>
      <el-select
        v-model="roleStatus"
        placeholder="角色状态"
        :clearable="false"
        style="width:130px;margin-left:15px"
        class="filter-item"
        @change="changeRoleStatus"
      >
        <el-option v-for="s in statusData" :key="s.key" :label="s.value" :value="s.key" />
      </el-select>
    </div>

    <el-table :data="rolesList" style="width: 100%;margin-top:10px;" border>
      <el-table-column align="center" label="角色ID" min-width="70">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column align="center" label="角色名称" min-width="100">
        <template slot-scope="scope">{{ scope.row.roleName }}</template>
      </el-table-column>
      <el-table-column align="center" label="角色状态" min-width="100">
        <template slot-scope="scope">{{ scope.row.roleStatus==1?'启用':'禁用' }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="200">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit"
            @click="handleEdit(scope)"
            v-if="scope.row.roleStatus==1"
          >编辑</el-button>
          <el-button
            type="danger"
            v-if="scope.row.roleStatus==1"
            icon="el-icon-close"
            size="small"
            @click="disableRole(scope)"
          >禁用</el-button>
          <el-button
            type="success"
            size="small"
            icon="el-icon-check"
            v-if="scope.row.roleStatus!=1"
            @click="enableRole(scope)"
          >启用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑角色':'新增角色'">
      <el-form
        :model="role"
        :rules="roleRules"
        ref="roleForm"
        label-width="80px"
        label-position="left"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="role.roleName" placeholder="角色名称" />
        </el-form-item>
        <!-- <el-form-item label="Desc">
          <el-input
            v-model="role.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="Role Description"
          />
        </el-form-item>-->
        <el-form-item label="功能菜单">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="routesData"
            :props="defaultProps"
            show-checkbox
            node-key="path"
            @check="treeNodeCheck"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import vPinyin from '@/utils/pinyin'
import {
  getRoutes,
  getRoles,
  addRole,
  deleteRole,
  enableRole,
  updateRole,
  getRoleById
} from '@/api/role'

const defaultRole = {
  id: '',
  roleName: '',
  roleEngName: '',
  roleStatus: '',
  routes: []
}
export default {
  data() {
    return {
      roleStatus: 1,
      statusData: [
        { key: 1, value: '启用' },
        { key: 0, value: '禁用' }
      ],
      role: Object.assign({}, defaultRole),
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      functionIds: [],
      roleRules: {
        roleName: [
          { required: true, message: '角色名不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    routesData() {
      // console.log('tree#######################', this.routes)
      return this.routes
    }
  },
  created() {
    // Mock: get all routes and roles list from server
    this.getRoutes()
    this.getRoles(1)
  },
  methods: {
    changeRoleStatus(status) {
      this.getRoles(status)
    },
    treeNodeCheck() {
      this.checkStrictly = false
    },
    async getRoutes() {
      //从服务器获取所有的路由信息
      const res = await getRoutes()
      this.serviceRoutes = res.data
      console.log('res.data', res.data)
      this.routes = this.generateRoutes(res.data)
    },
    async getRoles(roleStatus) {
      //从服务器查询出所有的角色以及它的路由信息
      const res = await getRoles(roleStatus)
      this.rolesList = res.data
      // console.log(res.data)
    },

    //根据路由信息生成树状结构
    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        // if (route.hidden) {
        //   continue
        // }

        const onlyOneShowingChild = this.onlyOneShowingChild(
          route.children,
          route
        )
        // console.log('onlyOneShowingChild', onlyOneShowingChild)
        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.functionUrl),
          title: route.functionName
        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      console.log('restree', res)

      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach((route) => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleAddRole() {
      this.checkStrictly = false
      this.role = Object.assign({}, defaultRole)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      //远程获取特定角色权限
      getRoleById(scope.row.id).then((res) => {
        if (res.code == 20000) {
          if (res.data.functionList) {
            this.role.routes = res.data.functionList
          } else {
            this.role.routes = []
          }
          this.role.id = res.data.role.id
          this.role.roleName = res.data.role.roleName
          this.role.roleEngName = res.data.role.roleEngName
          // console.log('this.role', this.role)
          this.$nextTick(() => {
            this.checkStrictly = true
            //获取对应角色的路由，给树上节点打勾
            console.log('cccccccccccccccccccccc', this.role.routes)
            const routes = this.generateRoutes(this.role.routes)
            console.log('aaaaaaaaaaaaaaaa', routes)
            // console.log('ttttttttttttttt', this.generateArr(routes))
            //generateArr方法将树状结构转换成单链数组，用于给节点打勾
            console.log('dddddddddddddddddddd', this.generateArr(routes))
            this.$refs.tree.setCheckedNodes(this.generateArr(routes))
            // set checked state of a node not affects its father and child nodes
          })
        } else {
          this.$notify({
            title: '失败',
            message: '获取角色失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    enableRole({ $index, row }) {
      this.$confirm('确定是否要启用该角色?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        enableRole(row.id)
          .then((res) => {
            if (res.code == 20000) {
              this.$notify({
                title: '成功',
                message: '角色启用成功',
                type: 'success',
                duration: 2000
              })
              this.getRoles(1)
            } else {
              this.$notify({
                title: '失败',
                message: '角色启用失败',
                type: 'error',
                duration: 2000
              })
            }
          })
          .catch((err) => {
            console.error(err)
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      })
    },
    disableRole({ $index, row }) {
      this.$confirm('确定是否要禁用该角色?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          deleteRole(row.id).then((res) => {
            if (res.code == 20000) {
              this.$notify({
                title: '成功',
                message: '角色禁用成功',
                type: 'success',
                duration: 2000
              })
              this.getRoles(0)
            } else {
              this.$notify({
                title: '失败',
                message: '角色禁用失败',
                type: 'error',
                duration: 2000
              })
            }
          })
        })
        .catch((err) => {
          console.error(err)
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []
      console.log('routes', routes)
      for (const route of routes) {
        const routePath = path.resolve(basePath, route.functionUrl)

        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(
            route.children,
            routePath,
            checkedKeys
          )
        }

        if (
          checkedKeys.includes(routePath) ||
          (route.children && route.children.length >= 1)
        ) {
          res.push(route)
        }
      }
      return res
    },
    //确认保存新建角色的权限
    async confirmRole() {
      const isEdit = this.dialogType === 'edit'

      const checkedKeys = this.$refs.tree.getCheckedKeys()
      console.log('checkedKeys', checkedKeys)
      this.role.routes = this.generateTree(
        deepClone(this.serviceRoutes),
        '/',
        checkedKeys
      )

      // console.log('确定修改的权限树', this.role.routes)

      if (isEdit) {
        // await updateRole(this.role.id, this.role)
        // for (let index = 0; index < this.rolesList.length; index++) {
        //   if (this.rolesList[index].id === this.role.id) {
        //     this.rolesList.splice(index, 1, Object.assign({}, this.role))
        //     break
        //   }
        // }
        this.functionIds = []
        this.recursionNodeId(this.role.routes)
        updateRole({
          roleId: this.role.id,
          roleName: this.role.roleName,
          // roleEngName: this.role.roleEngName,
          functionIds: this.functionIds
        }).then((res) => {
          if (res.code == 20000) {
            this.$notify({
              title: '成功',
              message: '角色修改成功',
              type: 'success',
              duration: 2000
            })
            this.getRoles(1)
          } else {
            this.$notify({
              title: '失败',
              message: '角色修改失败',
              type: 'error',
              duration: 2000
            })
          }
        })
      } else {
        this.functionIds = []
        this.recursionNodeId(this.role.routes)
        // console.log(
        //   this.role.roleName,
        //   vPinyin.chineseToPinYin(this.role.roleName),
        //   this.functionIds
        // )
        this.$refs.roleForm.validate((valid) => {
          if (valid) {
            addRole({
              roleName: this.role.roleName,
              roleEngName: vPinyin
                .chineseToPinYin(this.role.roleName)
                .toLowerCase(),
              functionIds: this.functionIds
            }).then((res) => {
              if (res.code == 20000) {
                this.$notify({
                  title: '成功',
                  message: '新增角色成功',
                  type: 'success',
                  duration: 2000
                })
                this.getRoles(1)
              } else {
                this.$notify({
                  title: '失败',
                  message: '新增角色失败',
                  type: 'error',
                  duration: 2000
                })
              }
            })
          } else {
            this.$notify({
              title: '失败',
              message: '验证失败',
              type: 'error',
              duration: 2000
            })
          }
        })

        // const { data } = await addRole(this.role)
        // this.role.key = data.key
        // this.rolesList.push(this.role)
      }

      const { id, roleName } = this.role
      this.dialogVisible = false
      this.$notify({
        title: '修改对象',
        dangerouslyUseHTMLString: true,
        message: `
            <div>角色ID: ${id}</div>
            <div>角色名称: ${roleName}</div>
          `,
        type: 'success'
      })
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      console.log('children', children)
      let onlyOneChild = null
      if (children == null) {
        children = []
      }
      // const showingChildren = children.filter((item) => !item.hidden)
      const showingChildren = children

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.functionUrl = path.resolve(
          parent.functionUrl,
          onlyOneChild.functionUrl
        )
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ...parent, functionUrl: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    },

    //递归获取所有节点id
    recursionNodeId(routes) {
      for (let r of routes) {
        this.functionIds.push(r.id)
        if (r.children != null && r.children.length > 0) {
          this.recursionNodeId(r.children)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
